package com.globallogic.vkulyk.PrimeNumbersFinder;

import java.util.*;

/**
 * The class finds prime numbers which are smaller or equal to the inputed from
 * keyboard integer number. Prime numbers - integral numbers that are not evenly
 * divisible by any other numbers except for themselves and 1. For example, for
 * input number 6, the output of the program is: [2, 3, 5]
 * 
 * @author Viacheslav Kulyk
 * @version 1.1 30 Jan 2013
 */
public class PrimeNumbersFinder {

	private int maxNumber = 0;
	private int[] primeNumbers = new int[1000];
	private int maxIndex = 0;

	public static void main(String[] args) {
		new PrimeNumbersFinder().findPrimeNumbers();
	}

	private void findPrimeNumbers() {
		if (getMaxNumber()) {
			calculatePrimeNumbers();
			printPrimeNumbers();
		}
	}

	private boolean getMaxNumber() {
		Scanner scanner = new Scanner(System.in);
		System.out.print("Enter number and press 'Enter' key:");
		try {
			maxNumber = scanner.nextInt();
			return true;
		} catch (InputMismatchException ime) {
			System.out.println("Illegal input. Exiting.");
			return false;
		}
	}

	private void calculatePrimeNumbers() {
		for (int number = 2; number <= maxNumber; number++) {
			boolean isPrime = true;
			for (int i = 2; i < number; i++) {
				if (number % i == 0) {
					isPrime = false;
					break;
				}
			}
			if (isPrime) {
				primeNumbers[maxIndex++] = number;
			}
		}
	}

	private void printPrimeNumbers() {
		System.out.print("[");
		for (int index = 0; index < maxIndex; index++) {
			if (index < (maxIndex -1)) {
				System.out.print(primeNumbers[index] + ",");
			} else {
				System.out.print(primeNumbers[index]);
			}
		}
		System.out.print("]");
	}
}
